package com.poetry.vup.user.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.poetry.vup.common.entity.user.VupUserDO;
import com.poetry.vup.common.entity.user.VupUserInfoDO;
import com.poetry.vup.common.redis.RedisStringService;
import com.poetry.vup.common.result.page.BasePage;
import com.poetry.vup.common.result.BaseResult;
import com.poetry.vup.common.util.JacksonUtil;
import com.poetry.vup.common.util.jwt.JwtTokenGenerator;
import com.poetry.vup.common.util.jwt.JwtTokenUtil;
import com.poetry.vup.user.domain.VupUserDTO;
import com.poetry.vup.user.domain.VupUserInfoDTO;
import com.poetry.vup.user.domain.VupUserVO;
import com.poetry.vup.user.service.VupUserAuthService;
import com.poetry.vup.user.service.VupUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/vupUser")
@CrossOrigin
@Slf4j
public class VupUserAuthController {

    @Autowired
    private VupUserAuthService vupUserAuthService;

    @Autowired
    private RedisStringService redisStringService;

    @Autowired
    private JwtTokenGenerator jwtTokenGenerator;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private VupUserInfoService vupUserInfoService;

    /**
     * 查找所有的用户
     * @return
     */
    @RequestMapping(value = "/findAllVupUser",method = RequestMethod.POST)
    public BaseResult findAllVupUser(@RequestParam("pageSize") int pageSize,@RequestParam("pageNum")int pageNum){

        BaseResult result = BaseResult.failed("查询失败");

        BasePage<VupUserVO> voPage = new BasePage<>();
        BasePage<VupUserVO> basePage = vupUserAuthService.findAllVupUser(pageSize,pageNum);
        voPage.setPageNum(basePage.getPageNum());
        voPage.setList(basePage.getList());
        voPage.setPageSize(basePage.getPageSize());
        voPage.setTotal(basePage.getTotal());
        voPage.setTotalPage(basePage.getTotalPage());
        result = BaseResult.success(voPage);
        return result;
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public BaseResult userLogin(@RequestParam("userName")String userName, @RequestParam("passWord")String passWord,
                                HttpServletRequest request, HttpServletResponse response){
        BaseResult baseResult = BaseResult.failed("登录失败");
        //1.判断用户信息与密码信息是否为空
        if(StringUtils.isBlank(userName)) {
            return BaseResult.failed("用户名不能为空");
        }
        if(StringUtils.isBlank(passWord)) {
            return BaseResult.failed("密码不能为空");
        }

        VupUserDO vupUserDO = vupUserAuthService.findByUserName(userName);
        if(!vupUserDO.getUserPassord().equals(passWord)){
            return BaseResult.failed("密码不正确，请从新输入");
        }

        VupUserVO userVO = vupUserAuthService.findUserNameAndPassWord(userName,passWord);

        if(vupUserDO != null){
            //如果是第一次登录生成token
            if(StringUtils.isBlank(userVO.getUniqueIdentification())){
                //生成唯一标识做key
                String str = UUID.randomUUID().toString().replace("-","");
                userVO.setUniqueIdentification(str);
                int d = vupUserAuthService.update(JacksonUtil.objectToObject(userVO, VupUserDTO.class));
                //生成token
                String token = jwtTokenGenerator.generateToken(userName, passWord, str);
                //把token存入redis
                redisStringService.setEx(str,token,1*60*24, TimeUnit.MINUTES);
                userVO.setToken(token);
                response.addHeader("Authorization",token);
                response.addHeader("userId",userVO.getId());
            }else{
                Set<String> keys = redisStringService.keys(userVO.getUniqueIdentification());
                if(keys != null){
                    //删除之前的key
                    redisStringService.delete(keys);
                }
                String token = jwtTokenGenerator.generateToken(userName, passWord, userVO.getUniqueIdentification());
                //把token存入redis
                redisStringService.setEx(userVO.getUniqueIdentification(),token,10, TimeUnit.MINUTES);
                userVO.setToken(token);
                response.addHeader("Authorization",token);
                response.addHeader("userId",userVO.getId());
            }

            //添加个人信息
            VupUserInfoDO userInfoDO = vupUserInfoService.findById(Long.valueOf(userVO.getId()));
            if(userInfoDO == null){
                VupUserInfoDO vupUserInfoDO = new VupUserInfoDO();
                vupUserInfoDO.setId(Long.valueOf(userVO.getId()));
                vupUserInfoService.addUserInfo(JacksonUtil.objectToObject(vupUserInfoDO, VupUserInfoDTO.class));
            }
            baseResult = BaseResult.success(userVO);

        }else {
            baseResult = BaseResult.failed("该用户没有注册");
        }

        return baseResult;

    }

    /**
     * 登出
     */
    @PostMapping("/loginout")
    public BaseResult loginOut(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isBlank(authorization)){
           return BaseResult.unauthorized(null);
        }
        String userToken = jwtTokenUtil.getUserToken(authorization);
        redisStringService.delete(userToken);
        return BaseResult.success("登出成功");
    }


}
